package service

import (
	"goftp.io/server/core"
	"goftp.io/server/driver/file"
	"log"
	"sync"
)

var ftpHub map[int64]*core.Server
var ftpLock *sync.Mutex

func init() {
	ftpHub = make(map[int64]*core.Server)
	ftpLock = &sync.Mutex{}
}

func StartFtp(root string, port int64, user, pass string) {
	if _, ok := ftpHub[port]; ok {
		//已经有开启的服务了，就不再启动了
		return
	}
	Name := "FTP Server"
	var perm = core.NewSimplePerm("AAA", "BBB")

	// Server options without hostname or port
	opt := &core.ServerOpts{
		Name: Name,
		Factory: &file.DriverFactory{
			RootPath: root,
			Perm:     perm,
		},
		Auth: &core.SimpleAuth{
			Name:     user, // FTP 账号
			Password: pass, // FTP 密码
		},
		Port: int(port),
	}
	s := core.NewServer(opt)
	ftpLock.Lock()
	ftpHub[port] = s
	ftpLock.Unlock()
	err := s.ListenAndServe()
	if err != nil {
		log.Fatal("Error starting server:", err)
	}
}

func StopFtp(port int64) error {
	ftpLock.Lock()
	defer ftpLock.Unlock()
	if s, ok := ftpHub[port]; ok {
		delete(ftpHub, port)
		return s.Shutdown()
	}
	return nil
}
